package com.heima.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.crm.common.contents.CommonMessageContent;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.common.utils.BaseContext;
import com.heima.crm.mapper.CrUserMapper;
import com.heima.crm.mapper.SysDicTypeMapper;
import com.heima.crm.pojos.dtos.DicTypePageDTO;
import com.heima.crm.pojos.entity.SysDictType;
import com.heima.crm.pojos.entity.TbUser;
import com.heima.crm.service.SysDicTypeService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class SysDicTypeServiceImpl implements SysDicTypeService {
    @Autowired
    private SysDicTypeMapper sysDicTypeMapper;
    @Autowired
    private CrUserMapper crUserMapper;
    @Override
    public Result add(SysDictType sysDictType) {
        //重名
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<SysDictType>()
                .eq(SysDictType::getDictName, sysDictType.getDictName());
        SysDictType one = sysDicTypeMapper.selectOne(wrapper);
        if (one!=null && !"".equals(one)){
            return Result.error("字典名称已存在");
        }
        //创建人
        Long currentId = BaseContext.getCurrentId();
        TbUser tbUser = crUserMapper.selectById(currentId);
        sysDictType.setCreateBy(tbUser.getUserName());
        //创建时间
        sysDictType.setCreateTime(LocalDateTime.now());
        sysDicTypeMapper.insert(sysDictType);
        return Result.success();
    }

    @Override
    public Result findList(DicTypePageDTO dto) {
        LambdaQueryWrapper<SysDictType> wrapper = new LambdaQueryWrapper<>();
        if (dto.getDictName()!=null && !"".equals(dto.getDictName())){
            wrapper.like(SysDictType::getDictName,dto.getDictName());
        }
        if (dto.getDictType()!=null && !"".equals(dto.getDictType())){
            wrapper.like(SysDictType::getDictType,dto.getDictType());
        }
        if (dto.getStatus()!=null && !"".equals(dto.getStatus())){
            wrapper.eq(SysDictType::getStatus,dto.getStatus());
        }
        if (dto.getBegin()!=null && dto.getEnd()!=null){
            wrapper.between(SysDictType::getCreateTime,dto.getBegin(),dto.getEnd());
        }
        IPage page=new Page(dto.getPage(),dto.getSize());
        page = sysDicTypeMapper.selectPage(page, wrapper);
        PageResult pageResult = new PageResult(page.getTotal(), page.getRecords());
        return Result.success(pageResult);
    }

    @Override
    public Result findById(Long dicId) {
        SysDictType sysDictType = sysDicTypeMapper.selectById(dicId);
        return Result.success(sysDictType);
    }

    @Override
    public Result update(SysDictType sysDictType) {
        //重名
        sysDicTypeMapper.updateById(sysDictType);
        return Result.success();
    }

    @Override
    public Result deleteById(Long dicId) {
        sysDicTypeMapper.deleteById(dicId);
        return Result.success();
    }

    @Override
    public Result deleteByIds(List<Long> ids) {
        sysDicTypeMapper.deleteByIds(ids);
        return Result.success();
    }

    @Override
    public Result allDictName() {
        List<String> list=sysDicTypeMapper.allDictName();
        return Result.success(list);
    }

    @Override
    public Result export(HttpServletResponse response, List<Long> ids) {
        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/dict_export.xlsx");
        List<SysDictType> list = sysDicTypeMapper.selectBatchIds(ids);
        if (list == null) {
            return Result.error("没有数据");
        }
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            for (int j = 0; j < list.size(); j++) {
                XSSFRow row = sheet.createRow(j + 1);
                row.createCell(0).setCellValue(list.get(j).getDictId());
                row.createCell(1).setCellValue(list.get(j).getDictName());
                row.createCell(2).setCellValue(list.get(j).getDictType());
                row.createCell(3).setCellValue(list.get(j).getStatus());
                row.createCell(4).setCellValue(list.get(j).getRemark());
                row.createCell(5).setCellValue(list.get(j).getCreateTime());
            }

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException("导出失败！");
        }
        //3. 通过输出流将Excel文件下载到客户端浏览器

        return Result.success();
    }


}
